from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from meiduo_mall import settings
from itsdangerous import BadData


# 因为openid属于敏感数据, 而且openid在获取后会传递给前端的, 所以不能明文显示
# itsdangerous 可以提供有 有效期的Token
# django自带有签名加密处理


# 对openid进行加密处理
def generate_eccess_token(openid):
    # serializer = Serializer(密钥, 有效期秒)
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)

    # serializer.dump(数据), 返回bytes类型 所以在返回时需要解码成字符串
    token = serializer.dumps({'openid':openid})

    return token.decode()

# 对加密的openid进行解密处理(access_token是加密后的openid)
def check_access_token(access_token):
    serializer = Serializer(settings.SECRET_KEY, expires_in=3600)

    # 对openid进行解密处理
    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')